#! /usr/bin/python
# -*- coding: cp1250 -*-

import glob
import re
import sys
import os

# removing dependencies from pepe library in this case
# because this is good demonstration file for python beginners
# they are to be able to run it as standalone script 

#import pepe.p_txt.bigtxt as bt

class lines:
    ''' read big text file as iterator
    '''
    def __init__(self , flpath_s):
        self.flpath_s = flpath_s
        self.sfile_fl = open(flpath_s, 'rb') 
    def __getitem__( self , index ):
        line_s = self.sfile_fl.readline()
        if line_s:
            return line_s
        else:
            raise IndexError

def srch(pattern, filesmask, otype='file-and-line', ofile='srch_results_appended', n='\x0D\x0A'):
    '''
    Purpose: Search txt files using regex.
    Syntax: srch <search string> <filesmask> [nonbare/bare] [ofile] 
    Example: srch \"^ERROR\" *.csv srch_err.txt bare
    
    bare  : omit source file name and row number
    ofile : if ofile is given, previous option (nobare/bare) as well
    '''

    print pattern, filesmask, otype, ofile

    # ofile='srch_results_appended' is normally used when calling 
    # p_utils.srch multiple times, meaning that output is most probably 
    # expected to be appended not rewritten
    if ofile == 'srch_results_appended': 
        of = open(ofile, 'ab')
    else:
        of = open(ofile, 'wb')
    for infile in glob.glob(filesmask):
        lino = 0
        #for line in bt.lines(infile):
        for line in lines(infile):

            line = re.sub('\x0D\x0A', '', line)
            line = re.sub('\x0D', '', line)
            line = re.sub('\x0A', '', line)
            lino += 1

            if re.search(pattern, line):
                if otype == 'file-and-line':
                    of.write(infile + '^' + str(lino) + '^\t' + line + n)
                elif otype == 'bare':
                    of.write(line + n)
                else:
                    of.write(line + n)
    of.close()
    return 1

if __name__ == '__main__':
    '''
	import pepe.p_win32.getOsVersion as pwg
	if pwg.main() == 'MS Windows XP, SP2, v5.1, 32bit':
    os.system('@chcp 1250')
    '''
    if len(sys.argv)    == 3:
        srch(sys.argv[1], sys.argv[2])
    elif len(sys.argv)  == 4:
        srch(sys.argv[1], sys.argv[2], sys.argv[3])
    elif len(sys.argv)  == 5:
        srch(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    else:
        print srch.__doc__
